#pragma once

#ifndef _WEBKIT_NEW

#include <json/json.h>
#include "WebPacketHead.h"
#include "cstTime.h"
#include "VARBinary.h"

using namespace std;

class CJSONField;
class CXXTEA;
class CParamSys_Base;
class CWebPacket
{
public:
	CWebPacket(intptr_t &buildRet, const char * recvBuf, intptr_t recvLen, const CParamSys_Base *pParam, bool doBuildJson, bool doReplace);
	CWebPacket(const stPreData *pPre, byte mStep, byte sStep);
	~CWebPacket();
	void clear();

	char * m_orgStr;
	CVARBinary m_code;
	bool GetIntField(const CJSONField &field, int &value) const;
	LPCWSTR GetWSTRField(const CJSONField &field, UINT codePage) const;
	LPCSTR GetSTRField(const CJSONField &field) const;
	bool SetField(const CJSONField &field, int value);
	bool SetField(const CJSONField &field, LPCSTR value);
	static char* EncodeParam(const char * src, intptr_t srcLen, bool isUTF8, CXXTEA *pPacketTea, intptr_t * pDestLen = nullptr);
	static char* DecodeParam(const char * src, intptr_t srcLen, bool isUTF8, CXXTEA *pPacketTea, intptr_t * pDestLen = nullptr);

	Json::Value m_root;
protected:
	CWebPacketHead m_head;

	bool buildJson();
	bool buildJson_real();
	LPCSTR getJsonString();
	LPCSTR getJsonString_real();
	bool GetIntField_real(const CJSONField &field, int &value) const;
	LPCWSTR GetWSTRField_real(const CJSONField &field, UINT codePage) const;
	LPCSTR GetSTRField_real(const CJSONField &field) const;
	const Json::Value* GetField(const CJSONField &field) const;
	bool SetField_real(const CJSONField &field, int value);
	bool SetField_real(const CJSONField &field, LPCSTR value);

public:
	intptr_t mainStep() const { return m_head.getMainStep(); }
	intptr_t subStep() const { return m_head.getSubStep(); }
	CWebPacketHead* getHead(){ return &m_head; }
	void setParam(const stPreData *pPre, byte mStep, byte sStep)
	{
		if (!pPre)
			m_head.setStep(false, mStep, sStep);
		else
		{
			m_head.setStep(true, mStep, sStep); m_head.setPreData(pPre);
		}
	}
	bool setParam(const char * param, bool doBuildJson);
	bool setParam(const stPreData *pPre, byte mStep, byte sStep, const char * param, bool doBuildJson);
	bool setParam(Json::Value &root, bool doBuildStr);
	bool setParam(const stPreData *pPre, byte mStep, byte sStep, Json::Value &root, bool doBuildStr);
	intptr_t build(const char * recvBuf, intptr_t recvLen, const CParamSys_Base *pParam, bool doBuildJson, bool doReplace);
	void writeLog(const CPlainTime& plain, LPCWSTR tag, bool repInvisible, LPCWSTR resRoot);
	bool changePrice(intptr_t price);
	const char* buildSend(intptr_t &sendLen, const CParamSys_Base *pParam, bool buildFromJson, CVARBinary *buffer = nullptr);
};

#endif	//_WEBKIT_NEW
